# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  # This module gives you the require_role helpers, and others.
  include RoleRequirementSystem
  
  before_filter :set_language
  
  before_filter :set_navigation_vars
  
  before_filter :initialize_cart
  
  before_filter :set_default_title
  
  simple_localization :language => :en
  
  def set_language
    begin
      raw = request.env["HTTP_ACCEPT_LANGUAGE"]
      parts = raw.split(';')
      found = false
      parts[0].split(',').each do |lang|
        if lang == "es"
          puts "Using Spanish"
          use_language 'es'
          found = true
          break
        elsif lang == 'en'
          puts "Using English"
          use_language 'en'
          found = true
          break
        end
      end
      use_language 'en' unless found
    rescue
        puts "Using English_2"
        use_language 'en'
    end
  end
  
  def set_navigation_vars
    @regions = Region.find(:all)
    @root_categories = Category.find_all_by_parent_id(nil)
    
    if controller_name == "categories"
      @categories = Category.find_all_by_parent_id(params[:id])
    else
      @categories = Category.find_all_by_parent_id(nil)
    end
  end
  
  def set_default_title
    @page_title = "Empower Artists"
    @page_title += " | #{params[:controller].humanize}" if params[:controller]
    @page_title += " | #{params[:action].humanize}" if params[:action]
    @page_title += " | #{params[:id]}" if params[:id]
  end
  
  helper :all # include all helpers, all the time
  layout proc{ |c| c.request.xhr? ? false : "customer" } #i'm done

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => '9a86f7a9566f208a0bbfd54f44992f53'
  
  def initialize_cart
    @cart = nil
    @cart = Cart.find_by_id(session[:cart_id]) if session[:cart_id]
    if @cart.nil?
      @cart = Cart.create
      session[:cart_id] = @cart.id      
    end
  end
  
  private
  def use_language lang
    sym = lang.to_sym
    
    #simple_localization :language => sym
    Localization.use sym
    @lang = lang.to_s
  end
end
